<?php

/**
 * 开放接口 - 菠萝派对接
 * Class BoluopaiAction
 * @author lilei<LL_strive@163.com> 2017-04-10
 */
class BoluopaiAction extends Action
{

    /**
     * 接口要求: 所有开发接口只有一个URL入口, 通过不同的method来进行不同的接口服务,
     *         该index()方法就是所有接口服务的入口
     * 1. 在此方法中先进行签名验证
     * 2. 根据不同的method来执行不同的接口
     */
    public function index()
    {

        /** 1. 获得http请求传参(此传参来自菠萝派) */
        $method     = $_REQUEST['method'];                  // 调用的接口方法名
        $appkey     = $_REQUEST['appkey'];                  // 商城(密友圈)的appkey
        $token      = $_REQUEST['token'];                   // 用户token(在菠萝派中添加的用户)
        $bizcontent = $_REQUEST['bizcontent'];              // 我需要的私有参数(除菠萝派平台抽象出的公共参数外内容)
        $sign       = $_REQUEST['sign'];                    // 菠萝派商城签名算法

        // 开放平台 - 查数据库secret
        Session::switchCustomer(0);
        // 实例化开发平台数据模型
        $OpenplatModel = M('module_openplat');
        // 开放平台查询筛选条件
        $openplatWhere['deleted'] = array('eq', 0);
        $openplatWhere['token']   = array('eq', $token);
        // 筛选出该token对应的appSecret, 用作鉴权
        $openplat = $OpenplatModel->where($openplatWhere)->field('appsecret, name')->find();
        $appSecret = $openplat['appsecret'];
        $name      = $openplat['name'];

        /** 2. 按照菠萝派加密算法进行验证 */
        $unsign     = $appSecret . "appkey" . $appkey . "bizcontent" . $bizcontent . "method" . $method . "token" . $token . $appSecret;
        $newsign    = md5(strtolower($unsign));

        if ($sign != $newsign) {     // 如果签名不一致, 则返回错误
            echo("{\"code\":\"40000\",\"message\":\"Logical Error\",\"subcode\":\"GSE.VERIFYSIGN_FAILURE\",\"submessage\":\"签名验证失败\"}");
        } else {                    // 如果签名一致, 则根据不同的方法执行特定操作
            switch ($method) {
                case 'Differ.JH.Business.GetOrder':             // 查询订单
                    $this->getOrder($bizcontent, $token, $name);
                    break;
                case 'Differ.JH.Business.CheckRefundStatus':    // 检测退款
                    $this->checkRefundStatus($bizcontent);
                    break;
                case 'Differ.JH.Business.Send':                 // 订单发货同步
                    return $this->send($bizcontent);
                    break;
//                case 'Differ.JH.Business.UpdateSellerMemo';     // 修改订单备注
//                    $this->updateSellerMemo($bizcontent);
//                    break;
                case 'Differ.JH.Business.AddPro':                //同步商品
                    return $this->addProduct($bizcontent);
                    break;
                case 'Differ.JH.Business.DownloadProduct':      // 下载商品
                    $this->downloadProduct($bizcontent, $token);
                    break;
                case 'Differ.JH.Business.SyncStock':            // 库存同步
                    return $this->syncStock($bizcontent);
                    break;
//                case 'Differ.JH.Business.GetRefund':            // 退货退款单
//                    $this->getRefund($bizcontent);
//                    break;
                default:                                // 如果无此接口, 则返回错误
                    echo json_encode(['code' => '40000', 'message' => 'Client Error', 'subcode' => 'GSE.ILLEGAL_ACCESS', 'submessage' => '未知的请求方法']);
                    break;
            }
        }

    }
    //增加商品
    protected function addProduct($bizcontent){
        $obj_bizcontent = json_decode($bizcontent,true);
        $id = $obj_bizcontent['id'];
        unset($obj_bizcontent['id']);
        Session::switchCustomer(0);
        $productModel= M('module_product');
        $result = $productModel->where("id=$id")->save($obj_bizcontent);
        return $result;
    }

    // > 1. 订单

    /**
     * 获得订单信息(商城平台 -> 菠萝派 -> 网店管家)
     *
     * @param $bizcontent   菠萝派传过来的私有变量
     * @param $token        菠萝派不同用户的token,用以区分用户身份[vendor|depot|...]
     */
    protected function getOrder($bizcontent, $token, $name)
    {
\Log::write('BLP_getOrder' . date('Y-m-d_H:i:s') . $bizcontent);
        /** 1. 获得菠萝派参数 */
        $obj_bizcontent = json_decode($bizcontent);
        $biz_orderStatus = $obj_bizcontent->OrderStatus;    // 订单交易状态(具体参数值含义看文档手册手册)
        $biz_platOrderNo = $obj_bizcontent->PlatOrderNo;    // 平台订单号
        $biz_startTime   = $obj_bizcontent->StartTime;      // 开始时间
        $biz_endTime     = $obj_bizcontent->EndTime;        // 截止时间
        $biz_timeType    = $obj_bizcontent->TimeType;       // 订单时间类别
        $biz_pageIndex   = $obj_bizcontent->PageIndex;      // 页码
        $biz_pageSize    = $obj_bizcontent->PageSize;       // 每页条数
        $biz_shopType    = $obj_bizcontent->ShopType;       //

        // 1.1 增加数据健壮性校验, 对必须参数进行验证
        // 对抓单参数并无严格要求

        /** 2. 实例化数据模型 */
        Session::switchCustomer(0);
        $orderModel       = M("module_product_order");
        $orderDetailModel = M("module_product_order_detail");
        $OpenplatModel    = M('module_openplat');
        $productModel     = M('module_product');
        $productSpeciModel= M('module_product_specification');
        $CustomerModel    = M('customer_user');

        /** 3. 查询订单数据 */
        // 3.1 匹配快递单号 !
        // 3.2 订单不可是删除了的订单
        $arrOrdersWhere['deleted'] = array('eq', 0);
        // 3.3 匹配订单类型!
        // 3.4 匹配配送方式 - 是否应该只匹配物流配送的
//        $arrOrdersWhere['deliveryType'] = array('eq', 'delivery');
        // 3.5 匹配单号
        if (!empty($biz_platOrderNo)) { // 是否指定了某个订单
            $arrOrdersWhere['serialNumber'] = array('eq', $biz_platOrderNo);
        }
        // 3.6 batch ?!
        // 3.7 匹配电话号!
        // 3.8 匹配价格!
        // 3.9 匹配开始结束时间
        if ($biz_timeType == 'JH_01') { // 匹配时间区间 JH_01 => 订单修改时间
            $arrOrdersWhere['updateTime'] = array(array('egt', str_replace('+', ' ', $biz_startTime)), array('elt', str_replace('+', ' ', $biz_endTime)));
        } else { // 匹配时间区间 JH_02 => 订单创建时间
            $arrOrdersWhere['createTime'] = array(array('egt', str_replace('+', ' ', $biz_startTime)), array('elt', str_replace('+', ' ', $biz_endTime)));
        }
        // 3.10 匹配买家名称!
        // 3.11 匹配订单状态
        if (in_array($biz_orderStatus, ['JH_01', 'JH_02', 'JH_03', 'JH_04', 'JH_05'])) { // 限定订单状态, 否则选择全部
            $status = [
                'JH_01' => array('eq', 'payingconfirm'),
                'JH_02' => array('eq', 'delivering'),
                'JH_03' => array(array('eq', 'delivered'), array('eq', 'deliveredtostore'), 'or'),
                'JH_04' => array('eq', 'ok'),
                'JH_05' => array('eq', 'close'),
            ];
            $arrOrdersWhere['status'] = $status[$biz_orderStatus];
        } else {
            $arrOrdersWhere['status'] = array('eq', 'delivering');
        }
        // 3.12 匹配支付方式!
        // 3.13 匹配商品名称!
        // 3.14 匹配门店名称 - 如果需要,应该也做类似vendor的身份用户

        // 3.15 匹配特殊身份
        // 若做开放平台模块, 根据token查询vids
        // 开放平台筛选条件
        $openplatWhere['deleted'] = array('eq', 0);
        $openplatWhere['token']   = array('eq', $token);
        // 查询该token下供应链关系
        $openplat_ids = $OpenplatModel->where($openplatWhere)->field('vids, channelIds')->find();
        // 过滤供应商
        if (!empty($openplat_ids['vids'])) {    // 如果存在供应链,则筛选该供应链下的订单
            $arrOrdersWhere['vId'] = array('in', json_decode($openplat_ids['vids']));
        } else {                // 否则返回无
            $result = [
                'code'       => '10000',
                'message'    => 'SUCCESS',
                'subcode'    => '',
                'submessage' => '无相关供应链订单'
            ];
            echo json_encode($result);

            return;
        }
        // 供应商名下的各渠道
        if (!empty($openplat_ids['channelIds'])) {
            $CustomerWhere['id'] = array('in', json_decode($openplat_ids['channelIds']));
            $customerIds = $CustomerModel->where($CustomerWhere)->field('customerId')->select();

            $arr_customerIds = [];
            foreach ($customerIds as $index => $customerId) {
                array_push($arr_customerIds, $customerId['customerId']);
            }

            $arrOrdersWhere['fromCustomerId'] = array('in', $arr_customerIds);
        } else {
            $result = [
                'code'       => '10000',
                'message'    => 'SUCCESS',
                'subcode'    => '',
                'submessage' => '无相关渠道订单'
            ];
            echo json_encode($result);

            return;
        }

        // 3.16 处理页数, 如果没有设置, 则默认查全部符合
        if (empty($biz_pageIndex) || empty($biz_pageSize)) {
            $biz_pageIndex = 1;
            $biz_pageSize  = null;
        }

        $arrOrders = $orderModel
            ->where($arrOrdersWhere)
            ->field("id, serialNumber, status, createTime, address, fullName, phone, remark, sellerRemark,province,city,country,
                logisticsCost, price, points, payType, deliveryType, payTime, invoiceTitleName, IDNumber, IDName")
            ->order("id desc")
//            ->page($biz_pageIndex, $biz_pageSize)
            ->select();

        /** 4. 组合订单数据 */
        $payType = [
            'interact'  => '',
            'consume'   => '',
            'stored'    => '',
            'alipay'    => '支付宝支付',
            'wxpay'     => '微信支付',
            'delivery'  => '货到付款'
        ];
        $sendstyle = [
            'pickup'    => '门店自提',
            'delivery'  => '物流配送'
        ];
        $orders = [];
        foreach ($arrOrders as $order) {    // 遍历所有订单数据

            // 格式化地址, 分割省市区
            $Product = A('Product');
            if($order['province']){
                $address['province'] = $order['province'];
                $address['city'] = $order['city'];
                $address['area'] = $order['country'];
                $address['street'] = $order['address'];
                $order['address'] =  $order['province'].$order['city'].$order['country'].$order['address'];
            }else{
                $address = $Product->addressFomate($order['address']);
            }

            /** 4.1 总订单数据 */
            $arr_order = [
                "PlatOrderNo"               => $order['serialNumber'],
                "tradetime"                 => $order['createTime'],
                "payorderno"                => "",
                "country"                   => 'CN', // 国家二位码 写死 - 中国
                "province"                  => $address['province'],
                "city"                      => $address['city'],
                "area"                      => $address['area'],
                "town"                      => $address['street'],
                "address"                   => $order['address'],
                "zip"                       => "",
                "phone"                     => "",
                "mobile"                    => $order['phone'],
                "email"                     => "",
                "customerremark"            => $order['remark'],
                "sellerremark"              => $order['sellerRemark'],
                "postfee"                   => 0,//$order['logisticsCost'],
                //"goodsfee"                  => 0,
                //"totalmoney"                => $order['price'],
                "favourablemoney"           => 0,//$order['pointsice'],
                "commissionvalue"           => 0,
                "taxamount"                 => 0,
                "tariffamount"              => 0,
                "addedvalueamount"          => 0,
                "consumptiondutyamount"     => 0,
                "sendstyle"                 => $sendstyle[$order['deliveryType']],
                "qq"                        => '',
                "paytime"                   => $order['payTime'],
                "invoicetitle"              => $order['invoiceTitleName'],
                "codservicefee"             => 0,
                "cardtype"                  => 'JH_01',             // 写死 - 身份证
                "idcard"                    => $order['IDNumber'],
                "idcardtruename"            => $order['IDName'],
                "receivername"              => $order['fullName'],
                "nick"                      => $name,    // 网店管家中的网名, 涉及网店管家会计清账
                "ShouldPayType"             => $payType[$order['payTime']]
            ];
            // 整理订单状态数据
            if (in_array($order['status'], ['payingconfirm', 'delivering', 'delivered', 'deliveredtostore', 'ok', 'close'])) {
                $Ostatus = [
                    'payingconfirm'     => 'JH_01',
                    'delivering'        => 'JH_02',
                    'delivered'         => 'JH_03',
                    'deliveredtostore'  => 'JH_03',
                    'ok'                => 'JH_04',
                    'close'             => 'JH_05'
                ];
                $Ostatusdes = [
                    'payingconfirm'     => '等待买家付款',
                    'delivering'        => '等待卖家发货',
                    'delivered'         => '等待买家确认收货',
                    'deliveredtostore'  => '等待买家确认收货',
                    'ok'                => '交易成功',
                    'close'             => '交易关闭'
                ];
                $arr_order['tradeStatus']            = $Ostatus[$order['status']];
                $arr_order['tradeStatusdescription'] = $Ostatusdes[$order['status']];
            } else {
                $arr_order['tradeStatus']            = 'JH_99';
                $arr_order['tradeStatusdescription'] = '所有订单';
            }

            /** 4.2 查询订单中商品详情数据 */
            $arrOrderDetailsWhere['detail.oid'] = array('eq', $order['id']);
            $arrOrderDetails = $orderDetailModel
                ->alias("detail")
                ->join('wx_module_product product on detail.pid = product.id')
                ->join("wx_module_product_order_detail_specification specification ON detail.id = specification.did")
                ->where($arrOrderDetailsWhere)
                ->field("
                    detail.count as Dcount, detail.ppat as Dppat, detail.serialNumber as DserialNumber,
                    detail.customizedName1 as DcustomizedName1, detail.customizedDescription1 as DcustomizedDescription1,
                    detail.customizedName2 as DcustomizedName2, detail.customizedDescription2 as DcustomizedDescription2,
                    detail.customizedName3 as DcustomizedName3, detail.customizedDescription3 as DcustomizedDescription3,
                    product.id as Pid, product.name as Pname, product.supportSpecification as PsupportSpecification, product.supplyProId as PsupplyProId,
                    specification.firstSpecificName as SfirstSpecificName, specification.secSpecificName as SsecSpecificName")
                ->select();

            // 一个订单可以包含多个商品
            $goodsfee = 0;
            $goodinfos = [];
            foreach ($arrOrderDetails as $orderDetail) {    // 遍历所有商品详情

                $arr_goodinfo = [
                    'ProductId'      => $orderDetail['Pid'],
                    'suborderno'     => '',
                    'tradegoodsno'   => $orderDetail['DserialNumber'],
                    'tradegoodsname' => $orderDetail['Pname'],
                    'goodscount'     => $orderDetail['Dcount'],
                    'discountmoney'  => 0,
                    'taxamount'      => 0, // $orderDetail['Dppat'], 没有税额
                    'refundStatus'   => '',
                    'status'         => $arr_order['tradeStatus'],
                    'remark'         => ''
                ];
                // 商品供应商价格, 数据结束后有多规格商品价格的特殊处理(以20170427工作记录为主)
                if ($orderDetail['PsupportSpecification'] == 0) {   // 如果是单规格的商品的价格
                    $productWhere['id']           = array('eq', $orderDetail['PsupplyProId']);          // 在$orderDetail中查出这个商品的supplyProId(主商品id)
                    $productWhere['serialNumber'] = array('eq', $orderDetail['DserialNumber']);         // 确保准确, 非必要, 筛选条码相同的商品
                    $productWhere['vId']          = array('in', json_decode($openplat_ids['vids']));    // 确保准确, 非必要, 筛选供应商下商品

                    $productSupplyPrice = $productModel->where($productWhere)->getField('supplyPrice');
                    $arr_goodinfo['price'] = $productSupplyPrice;
                } else {    // 是多规格的商品的价格
                    $productSpeciWhere['pid']          = array('eq', $orderDetail['PsupplyProId']);
                    $productSpeciWhere['serialNumber'] = array('eq', $orderDetail['DserialNumber']);        // 确保准确, 非必要
                    // 不同供应商供应同一商品, 则商品编码是一致的(国标码嘛), 但是供应价格不一样, 所以这里需要筛选一下此供应商下的商品
                    $productWhere['vId']               = array('in', json_decode($openplat_ids['vids']));   // 确保准确, 非必要

                    $productSpeciSupplyPrice = $productSpeciModel->where($productSpeciWhere)->getField('supplyPrice');
                    $arr_goodinfo['price'] = $productSpeciSupplyPrice;
                }
                // 整理商品规格数据
                (!empty($orderDetail['SfirstSpecificName'])) ? $arr_goodinfo['tradegoodsspec'] .= $orderDetail['SfirstSpecificName'] . ', ' : '';
                (!empty($orderDetail['SsecSpecificName'])) ? $arr_goodinfo['tradegoodsspec'] .= $orderDetail['SsecSpecificName'] . ', ' : '';
                (!empty($orderDetail['DcustomizedName1'])) ? $arr_goodinfo['tradegoodsspec'] .= $orderDetail['DcustomizedName1'] . ':' . $orderDetail['DcustomizedDescription1'] . ', ' : '';
                (!empty($orderDetail['DcustomizedName2'])) ? $arr_goodinfo['tradegoodsspec'] .= $orderDetail['DcustomizedName2'] . ':' . $orderDetail['DcustomizedDescription2'] . ', ' : '';
                (!empty($orderDetail['DcustomizedName3'])) ? $arr_goodinfo['tradegoodsspec'] .= $orderDetail['DcustomizedName3'] . ':' . $orderDetail['DcustomizedDescription3'] : '';

                array_push($goodinfos, $arr_goodinfo);

                // 计算货款
                $goodsfee += $arr_goodinfo['price'] * $arr_goodinfo['goodscount'];
            }

            // 将订单商品详情数据加入订单中
            $arr_order['goodinfos'] = $goodinfos;

            // 处理货款, 合计应收
            $arr_order['goodsfee']   = $goodsfee;
            $arr_order['totalmoney'] = $arr_order['goodsfee'] + $arr_order['postfee'] - $arr_order['favourablemoney'];

            // 将所有订单数据放到$orders中返回
            array_push($orders, $arr_order);
        }

        /** 5. 返回接口数据 to 菠萝派 */
        $result = [
            'code'          => '10000',
            'message'       => 'SUCCESS',
            'numtotalorder' => count($orders),
            'orders'        => $orders
        ];

        echo json_encode($result);
    }

    /**
     * 检测订单退款状态接口(XXX -> 菠萝派 -> 商城平台)[没有内部实现]
     *
     * @param $bizcontent
     */
    protected function checkRefundStatus($bizcontent)
    {

        /** X. 返回数据 to 菠萝派 */
        $result = [
            'code'          => '10000',
            'message'       => 'SUCCESS',
            'refundStatus'  => 'JH_07'  // 没有退款
        ];
        echo json_encode($result);
    }

    /**
     * 订单发货接口(网店管家 -> 菠萝派 -> 商城平台)
     *
     * @param $bizcontent   菠萝派传过来的私有变量
     */
    protected function send($bizcontent) {
\Log::write('BLP_send' . date('Y-m-d_H:i:s') . $bizcontent);
        /** 1. 获得菠萝派参数 */
        $obj_bizcontent = json_decode($bizcontent);
        $biz_PlatOrderNo    = $obj_bizcontent->PlatOrderNo;     // 平台订单号
        $biz_LogisticNo     = $obj_bizcontent->LogisticNo;      // 快递运单号
        $biz_LogisticType   = $obj_bizcontent->LogisticType;    // 快递类别
        $biz_LogisticName   = $obj_bizcontent->LogisticName;    // 快递名称
        $biz_SendType       = $obj_bizcontent->SendType;        //
        $biz_IsSplit        = $obj_bizcontent->IsSplit;         // 是否拆单发货
        $biz_ShopType       = $obj_bizcontent->ShopType;        //
        $biz_SenderName     = $obj_bizcontent->SenderName;      // 发货人姓名
        $biz_SenderTel      = $obj_bizcontent->SenderTel;       // 发货人联系电话
        $biz_SenderAddress  = $obj_bizcontent->SenderAddress;   // 发货人地址
        $biz_IsHwgFlag      = $obj_bizcontent->IsHwgFlag;       // 是否为海外购
        $biz_DeliveryType   = $obj_bizcontent->DeliveryType;    //
        $biz_Goods          = $obj_bizcontent->Goods;           // 商品信息
        $resultType         = $obj_bizcontent->resultType;    // 快递名称
        // 1.1 增加数据健壮性校验, 对必须参数进行验证
        if (empty($biz_PlatOrderNo) || empty($biz_LogisticNo) || (empty($biz_LogisticType)&&empty($biz_LogisticName))) {
            $result = [
                'code'      => '40001',
                'message'   => 'ERROR',
                'subcode'   => 'PARAM_ERROR',
                'submessage'=> '参数异常'
            ];
            if(!$resultType){
                echo json_encode($result);
            }

            return false;
        }

        /** 2. 实例化数据模型 */
//        Session::switchCustomer(0);
//        $orderModel = M("module_product_order");

        /** 3. 执行发货操作修改 */
        $Product = A('Product');
        // 查询出cid写入session
        Session::switchCustomer(0);
        $OrderModel = M("module_product_order");
        $orderWhere['serialNumber'] = array('eq', $biz_PlatOrderNo);
        $order = $OrderModel->where($orderWhere)->field("id, fromCustomerId")->select();

        Session::$user['customerId'] = $order[0]['fromCustomerId'];
        $arr_expressNames = [
            'JH_107' => '秦远物流',
            'JH_006' => '中通速递',
            'JH_007' => '宅急送',
            'JH_069' => '邮政平邮/小包',
            'JH_037' => '邮政平邮/小包',
            'JH_002' => '圆通速递',
            'JH_145' => '运通快递',
            'JH_003' => '韵达快递',
            'JH_005' => '申通快递',
            'JH_014' => '顺丰快递',
            'JH_017' => '如风达',
            'JH_012' => '百世快递',
            'JH_004' => '天天快递',
            'JH_010' => '国通快递',
            'JHI_005' => 'FEDEX联邦(国内件）',
            'JH_001' => 'EMS',
            'JH_011' => '德邦',
            'JH_059' => '安能物流'
        ];

        if (array_key_exists($biz_LogisticType, $arr_expressNames)) {
            $expressName = $arr_expressNames[$biz_LogisticType];
        } else {
            $expressName = $biz_LogisticName;
        }
        // 阻止调内部方法时向页面输出内容, 否则接口对菠萝派报错
        ob_start();
        // 这里已经测试走进去了, 问题出在该方法内部
        // 如果调用updateOrderTipByOrderId方法(咱们平台这个发货操作是这个方法), 该方法内, session_init()就给我return了false, 所以抛去飞该部分功能, 调用updateOrderByOrderId方法
        $updateResult = $Product->updateOrderByOrderId($order[0]['id'], null, null, 'delivered', $expressName, $biz_LogisticNo);
        ob_end_clean();

        /** 4. 返回数据 to 菠萝派 */
        $result = [
            'code'      => '10000',
            'message'   => 'SUCCESS',
//            'subcode'   => 'GSE.SYSTEM_ERROR',
//            'submessage'=> '[20887]服务异常请稍后再试'
        ];
        if(!$resultType){
            echo json_encode($result);
        }
        return json_encode($result);

    }

    /**
     * 修改订单备注接口(网店管家 -> 菠萝派 -> 商城平台)
     *
     * @param $bizcontent   菠萝派传过来的私有变量
     */
    protected function updateSellerMemo($bizcontent)
    {

    }

    // > 2. 商品

    /**
     * 下载商品信息接口(网店管家 -> 菠萝派 -> 商城平台)
     *
     * @param $bizcontent   菠萝派传过来的私有变量
     * @param $token        菠萝派不同用户的token,用以区分用户身份[vendor|depot|...]
     *
     * ! 2017-04-23暂停更新编写
     */
    protected function downloadProduct($bizcontent, $token){
\Log::write('BLP_downloadProduct' . date('Y-m-d_H:i:s') . $bizcontent . ', token=' . $token);
        /** 1. 获得菠萝派参数 */
        $obj_bizcontent = json_decode($bizcontent);
        $biz_productId   = $obj_bizcontent->ProductId;    // 商品id
        $biz_productName = $obj_bizcontent->ProductName;  // 商品名称
        $biz_status = $obj_bizcontent->Status;       // 商品状态
        $biz_pageIndex = $obj_bizcontent->PageIndex;    // 页码
        $biz_pageSize = $obj_bizcontent->PageSize;     // 每页数量
        $biz_shopType = $obj_bizcontent->ShopType;     // 店铺类型:JH_01普通/02分销/03经销
        $biz_outskuid = $obj_bizcontent->OutSkuID;    // 查询批次号(亚马逊专用)
        $biz_outerId = $obj_bizcontent->OuterID;        // 外部商家编码

        /** 2. 实例化数据模型 */
        Session::switchCustomer(0);
        $ProductModel     = M("module_product");
        $OpenplatModel    = M('module_openplat');
        $ProductSpeciModel = M('module_product_specification');


        /** 3. 查询商品数据 */
        // 3.1 普通筛选
        $arrProductsWhere['deleted'] = array('eq', 0);
        ($biz_productId) ? $arrProductsWhere['id'] = array('eq', $biz_productId) : '';
        ($biz_productName) ? $arrProductsWhere['name'] = array("like", "%$biz_productName%") : '';
        if ($biz_status == 'JH_01') {
            $arrProductsWhere['isRemoved'] = array('eq', 0);
        } else if ($biz_status == 'JH_02') {
            $arrProductsWhere['isRemoved'] = array('eq', 1);
        }

        // 3.2 筛选该供应链下的商品? - 应该不会是所有商品数据
        $openplatWhere['deleted'] = array('eq', 0);
        $openplatWhere['token']   = array('eq', $token);
        // 查询该token下供应链关系
        $vids = $OpenplatModel->where($openplatWhere)->getField('vids');
        if (!empty($vids)) {    // 如果存在供应链,则筛选该供应链下的商品
            $arrProductsWhere['vId'] = array('in', json_decode($vids));
        } else {                // 否则返回无
            $result = [
                'code'       => '10000',
                'message'    => 'SUCCESS',
                'subcode'    => '',
                'submessage' => '无相关供应链商品'
            ];
            echo json_encode($result);

            return;
        }
        $arrProductsWhere['supplyProId']=array('exp',' is NULL');

        /** 4. 组合商品数据 */
        $arrProducts = $ProductModel
            ->where($arrProductsWhere)
            ->field("id, name,supplyProId, serialNumber, supplyPrice, inventoryCount, picUrl, supportSpecification,isRemoved")
            ->order("id desc")
            ->page($biz_pageIndex, $biz_pageSize)
            ->select();
\Log::write('BLP_downloadProduct_$arrProductsWhere_' . json_encode($arrProductsWhere));
\Log::write('BLP_downloadProduct_$arrProducts_' . $ProductModel->getLastSql());
        $count=$ProductModel->where($arrProductsWhere)->count();
        if($arrProducts['isRemoved'] == 0){
            $status = 'JH_01';
            $statusdesc1 = "已上架";
        }elseif($arrProducts['isRemoved'] == 1){
            $status = 'JH_02';
            $statusdesc1 = "已下架";
        }

        $arr_goodslist = [];    // 放置商品信息
        foreach ($arrProducts as $index => $product) {

            if ($product['supportSpecification'] == 0) {    // 不支持多规格
                $goodslist = [
                    'platproductid' => $product['id'],
                    'name' => $product['name'],
                    'outerid' => $product['serialNumber'],
                    'price' => $product['supplyPrice'],
                    'num' => $product['inventoryCount'],
                    'pictureurl' => $product['picUrl'],
                    'whsecode' => '商品暂不与仓库关联',
                    'status'=>$status,
                    'statusdesc'=>$statusdesc1,
                    'skus' => []
                ];

                array_push($arr_goodslist, $goodslist);
            } else if ($product['supportSpecification'] == 1) {//支持多规格
                $goodslist = [
                    'platproductid' => $product['id'],
                    'name' => $product['name'],
                    'outerid' => $product['serialNumber'],
                    'price' => $product['supplyPrice'],
                    'num' => $product['inventoryCount'],
                    'pictureurl' => $product['picUrl'],
                    'whsecode' => '商品暂不与仓库关联',
                    'status'=>$status,
                    'statusdesc'=>$statusdesc1,
                    'skus' => []
                ];
                $arrProductSpeciWhere['pid'] = array('eq', $product['id']);
                $arrProductSpecis = $ProductSpeciModel
                    ->where($arrProductSpeciWhere)
                    ->field("id, serialNumber, supplyPrice, inventoryCount, firstSpecificName, secSpecificName, firstSpecificUrl, secSpecificUrl")
                    ->select();
\Log::write('BLP_downloadProduct_$arrProductSpeciWhere_' . json_encode($arrProductSpeciWhere));
\Log::write('BLP_downloadProduct_$arrProductSpecis_' . $index . '__' . $ProductSpeciModel->getLastSql());
                $arr_skus = [];
                foreach ($arrProductSpecis as $index_speci => $speci) {
                    $skus = [
                        'skuid' => $speci['id'],                       //规格表id
                        'skuouterid' => $speci['serialNumber'],        //此规格条码
                        'skuprice' => $speci['supplyPrice'],           //此规格价格
                        'skuquantity' => $speci['inventoryCount'],     //此规格库存数
                        'skuname' => $speci['firstSpecificName'] . ', ' . $speci['secSpecificName'],     //规格名称
                        'skuproperty' => $speci['firstSpecificName'] . ', ' . $speci['secSpecificName'], //规格属性
                        'skupictureurl' => $speci['firstSpecificUrl']. ', ' . $speci['secSpecificUrl']   //规格图片
                    ];
                    array_push($arr_skus, $skus);
                }
                $goodslist['skus'] = $arr_skus;
                array_push($arr_goodslist, $goodslist);
            }

        }

        /** 5. 返回接口数据 to 菠萝派 */
        $result = [
            'code' => '10000',
            'message' => 'SUCCESS',
            'ishasnextpage'=>$biz_pageIndex,
            'totalcount' => $count,
            'goodslist'  => $arr_goodslist
        ];

        $json= json_encode($result);
\Log::write('BLP_downloadProductJson' . date('Y-m-d_H:i:s') . $json);
        echo $json;
    }

    /**
     * 库存同步接口(网店管家 -> 菠萝派 -> 商城平台)
     *
     * @param $bizcontent   菠萝派传过来的私有变量
     */
    protected function syncStock($bizcontent){
\Log::write('BLP_syncStock' . date('Y-m-d_H:i:s') . $bizcontent);
        $obj_bizcontent = json_decode($bizcontent);
        $biz_platproductid = $obj_bizcontent->PlatProductID;  //平台商品ID
        $biz_skuid         = $obj_bizcontent->SkuID;          //平台子规格ID
        $biz_outerid       = $obj_bizcontent->OuterID;        //外部商家编码
        $biz_quantity      = $obj_bizcontent->Quantity;       //库存数量
        $biz_syncstocktype = $obj_bizcontent->SyncStockType;  //库存更新方式
        $biz_shoptype      = $obj_bizcontent->ShopType;       //店铺类型
        $biz_outskuid      = $obj_bizcontent->OutskuID;       //外部商家SKU编号
        $returnType        = $obj_bizcontent->ReturnType;       //返回类型

        /**实例化数据库*/

        Session::switchCustomer(0);
        $ProductModel = M("module_product");
        $ProductSpeciModel = M('module_product_specification');
        $isSupSpeci=$ProductModel->where("id=$biz_platproductid")->getField('supportSpecification');
        if ($isSupSpeci==1) { //如果是多规格商品
            $arrProductSpeciWhere['id'] = array('eq', $biz_skuid);               //定义查询条件
            $arrProductSpeciWhere['pid'] = array('eq', $biz_platproductid);      //定义查询条件
            $PreQuantity=$ProductSpeciModel->where($arrProductSpeciWhere)->getField("inventoryCount");
            $arrProductSpeciSave['inventoryCount'] = $biz_quantity; //定义修改库存语句
            $arrProductSpeciSave['inventory'] =1; //定义修改库存语句
            $ProductSpeciModel->where($arrProductSpeciWhere)->save($arrProductSpeciSave); //修改库存
            $sql=$ProductSpeciModel->getlastsql();
\Log::write('BLP_getLastSql_$isSupSpeci==1' . date('Y-m-d_H:i:s') . $sql);
            $Quantity=$ProductSpeciModel->where($arrProductSpeciWhere)->getField("inventoryCount");
            $ProName=$ProductModel->where('id'==$biz_platproductid)->getField('name');
            $Speci1Name=$ProductSpeciModel->where($arrProductSpeciWhere)->getField("firstSpecificName");
            $Speci2Name=$ProductSpeciModel->where($arrProductSpeciWhere)->getField("secSpecificName");
        } else if($isSupSpeci==0){                 //如果是单规格商品
            $arrProductwhere['id'] = $biz_platproductid;         //定义查询条件
            $PreQuantity=$ProductModel->where($arrProductwhere)->getField('inventoryCount');
            $arrProductsave['inventoryCount'] = $biz_quantity;   //定义修改库存语句
            $arrProductsave['inventory'] =1; //定义修改库存语句
            $ProductModel->where($arrProductwhere)->save($arrProductsave);  //修改库存
            $sql=$ProductModel->getlastsql();
\Log::write('BLP_getLastSql_$isSupSpeci==0' . date('Y-m-d_H:i:s') . $sql);
            $Quantity=$ProductModel->where($arrProductwhere)->getField('inventoryCount');
            $ProName=$ProductModel->where($arrProductwhere)->getField('name');
        }

        $result = [
            'code'      => '10000',
            'message'   => 'SUCCESS',
            'Quantity'  => $Quantity
        ];

        $json= json_encode($result);
\Log::write('BLP_getLastSqlJson' . date('Y-m-d_H:i:s') . $json);
        echo $json;

        if($Quantity==0 && $PreQuantity!=0){
            $wxmessage=$ProName.'：'.$Speci1Name.$Speci2Name.'库存已经更改为0，赶紧去看看吧';
            $this->houjia($wxmessage);

        }elseif($PreQuantity==0 && $Quantity!=0){
            $wxmessage=$ProName.'：'.$Speci1Name.$Speci2Name.'库存已经从0更改为'.$Quantity.'，赶紧去看看吧';
            $this->houjia($wxmessage);
        }

    }

    protected function houjia($wxMessage){
        $url = 'http://test.mboxone.com/test/call.html?customerId=' . 3 . '&module=platMessage&method=index&params={"messageId":' . $wxMsgId . ',"toUserId":' . 57 . '}';
        $datas['first'] = array('value' => '您有新的消息', 'color' => "#743A3A");
        $datas['keyword1'] = array('value' => $wxMessage, 'color' => '#173177');
        $datas['keyword2'] = array('value' => '库存消息' . '-' . '库存消息', 'color' => '#173177');
        $datas['remark'] = array('value' => '。。', "color" => '#008000');
        TemplateMessage::send("o7pYBuHhsZwQCUSXudayoOEaT0NQ", 3, 'PlatMessage_OPENTM405762260', $url, $datas);
    }

    // > 3. 退款

    /**
     * 退货退款单下载接口(网店管家 -> 菠萝派 -> 商城平台)
     *
     * @param $bizcontent   菠萝派传过来的私有变量
     */
    protected function getRefund($bizcontent)
    {

    }

}
